import numpy as np
import sys
import os
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(current_dir, ".."))
import data_process.prepare_for_training as pr
#y=w*x+b
class LinearRegression:
    def __init__(self,data,labels):
        (data_processed,data_mean,data_std) = pr.prepare_for_training(data)
        self.data = data_processed
        self.labels = labels
        self.features_num = self.data.shape[1]
        self.samples_num = self.data.shape[0]
        self.data_mean = data_mean
        self.data_std = data_std
        self.w = np.zeros([self.features_num,1])

    def train(self,alpha=0.01,num_iteration=500):
        cost_history = self.gradient_descent(alpha,num_iteration)
        print("training finish!")
        return cost_history

    def gradient_descent(self,alpha,num_iterations):
        cost_history = []
        for i in range(num_iterations):
            self.gradient_step(alpha,cost_history)
        return cost_history

    def gradient_step(self,alpha,cost_history):
        prediction = np.dot(self.data,self.w)
        delta = prediction - self.labels
        cost_history.append((1/2)*np.dot(delta.T,delta)[0][0])
        w = self.w - alpha * (1.0/self.samples_num) * np.dot(delta.T, self.data).T
        self.w = w
    
    def predict(self,data):
        (process_data,mean,std) = pr.prepare_for_training(data)
        return np.dot(process_data,self.w)

        